<?php


namespace app\ptpay\controller;

use app\model\user\User;
use app\model\user\UserBill;
use app\ptpay\PtSdk;
use app\ptpay\model\Recharge;
use app\Request;

class WechatController{

    public function __construct()
    {
        $ptpay_config = array();

//派特支付的用户通讯秘钥
        $ptpay_config['paykey']='1bd451beef86cfba2519544c6fa73e8e';
//派特支付的用户id
        $ptpay_config['payUserID']='98502223192232';
//同步地址 替换为你的同步地址
        $ptpay_config['returnUrl']='http://'.$_SERVER['HTTP_HOST'].'/ptpay/wechat/pay_return';
//异步地址 替换为你的异步地址
        $ptpay_config['notifyUrl']='http://'.$_SERVER['HTTP_HOST'].'/ptpay/wechat/notify';
//微信用户信息获取的地址
        $ptpay_config['weChat_userInfo_returnUrl']='';
//是否返回页面,1是返回HTML,0是JSON数据
        $ptpay_config['isHtml']='3';
//访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
        $ptpay_config['transport'] = 'https://';
//派特支付的支付apiurl
        $ptpay_config['apiurl'] = 'pay.xdqj.net/createOrder';
//获取订单api
        $ptpay_config['getOrderApiUrl'] = 'pay.xdqj.net/getOrder';
//关闭订单api
        $ptpay_config['closeOrderApiUrl']  = 'pay.xdqj.net/closeOrder';
//获取微信用户信息
        $ptpay_config['getWeChatInfoApiUrl']  = 'pay.xdqj.net/welcome';

        $this->ptpay_config = $ptpay_config;
    }

    public function pay(Request $request)
    {
        $uid = $request->get('uid');
        $price = $request->get('price');
        $type = $request->get('type');

        $ptpay_config = $this->ptpay_config;

        //实例化SDK
        $pay = new PtSdk($ptpay_config);

        //创建订单需要构建的参数
        $parameter = array(
            //支付方式 1.是微信，2是支付宝
            "type" => $type,
            //商户订单号
            "payId" => build_order_no(),
            //自定义参数
            "param" => $uid,
            //金额
            "price" => $price,
            "returnUrl" => $ptpay_config['returnUrl'],
            "notifyUrl" => $ptpay_config['notifyUrl']
        );
        $recharge = new Recharge();
        $recharge->pay_id = $parameter['payId'];
        $recharge->order_id= "0";
        $recharge->type = $type;
        $recharge->param = $uid;
        $recharge->price = $price;
        $recharge->really_price= 0;
        $recharge->service_charge=0;
        $recharge->pay_order_type=0;
        $recharge->sign=0;
        $recharge->pay_time=date('Y-m-d H:i:s');
        $recharge->created_at = date('Y-m-d H:i:s');
        $recharge->save();



        // print_r($parameter);
        //创建订单,会自动跳转页面
        if($type==1) $yybtype=3;
        if($type==2) $yybtype=1;
        $yybdata = $parameter['payId'];
        $yybprice = $parameter['price'];
        $server = $_SERVER['HTTP_HOST'];
        $URL = "http://$server/phpdemo/codepay.php?type=$yybtype&data=$yybdata&money=$yybprice";
        header("Location: ".$URL);
        exit;
        // echo $pay->createOrder($parameter);

    }

    private function handle_notify($notify)
    {
        $pay_id = $notify['payId'];
        $order_id = $notify['orderId'];
        $param = $notify['param'];
        $type = $notify['type'];
        $price = $notify['price'];
        $really_price = $notify['reallyPrice'];
        $service_charge = array_key_exists('serviceCharge', $notify) ? $notify['serviceCharge'] : '0.00';
        $pay_order_type = array_key_exists('serviceCharge', $notify) ? $notify['serviceCharge'] : 0;
        $sign = $notify['sign'];

        //插入到充值列表
        $recharge = Recharge::where('pay_id', $pay_id)->find();
        //$recharge->pay_id = $pay_id;
        $recharge->order_id = $order_id;
        //$recharge->param = $param;
        //$recharge->type = $type;
        //$recharge->price = $price;
        $recharge->really_price = $really_price;
        $recharge->service_charge = $service_charge;
        $recharge->pay_order_type = $pay_order_type;
        $recharge->sign = "123";
        $recharge->pay_time = date('Y-m-d H:i:s');
        $recharge->save();

        if($price == $really_price){
            $uid = $param;
            $user = User::find($uid);
            $now_money = $user->now_money;
            $jine = floatval($price);
            //插入到用户充值列表
            $bill = new UserBill();
            $bill->uid = $uid;
            $bill->link_id = 0;
            $bill->pm = 1;
            $bill->title = "充值";
            $bill->category = "now_money";
            $bill->type = "recharge";
            $bill->number = number_format($jine, 2);
            $balance = (floatval($now_money) + $jine);
            $bill->balance = $balance;
            $bill->mark = "充值".number_format($jine, 2)."元";
            $bill->add_time = time();
            $bill->status = 1;
            $bill->take = 0;
            $bill->save();

            //给用户添加余额
            $user->now_money = $balance;
            $user->save();
        }
    }
    public function notify()
    {

        $i = $_POST;
        $notify['sign'] = $i['key'];
        if($notify['sign']!=="2c4809f6af6e1690213c9c4d9e333f4e"){
            exit('sing error');
        }
        $price = $i['money'];
        //插入到充值列表
        $recharge = Recharge::where('pay_id', $i['name'])->find();
        if($recharge){
            if($recharge['pay_order_type']==1){
                exit('订单已处理 error');
            }
            //改写订单
            $recharge->order_id = $i['ddh'];
            $recharge->really_price = $price;
            $recharge->pay_order_type = 1;
            $recharge->pay_time=$i['paytime'];
            $recharge->save();
            //开始写入
            $uid = $recharge['param'];
            $user = User::find($uid);
            $now_money = $user->now_money;
            $jine = floatval($price);
            //插入到用户充值列表
            $bill = new UserBill();
            $bill->uid = $uid;
            $bill->link_id = 0;
            $bill->pm = 1;
            $bill->title = "充值";
            $bill->category = "now_money";
            $bill->type = "recharge";
            $bill->number = number_format($jine, 2);
            $balance = (floatval($now_money) + $jine);
            $bill->balance = $balance;
            $bill->mark = "充值".number_format($jine, 2)."元";
            $bill->add_time = time();
            $bill->status = 1;
            $bill->take = 0;
            $bill->save();

            //给用户添加余额
            $user->now_money = $balance;
            $user->save();
            echo 'ok';
        }else{
            echo '单号错误';
        }

    }

    public function notify2()
    {
        $ptpay_config = $this->ptpay_config;

        $notify = $_GET;

        $pay = new PtSdk($ptpay_config);
        //验证签名
        if($pay->isSign())
        {
            //再次判断订单状态,如过服务器有这个订单就处理业务
            if($pay->isCheckOrder() || $pay->checkOrderState())
            {
                //签名验证成功,订单验证成功
                //---------开始业务逻辑----------------
                $request_data =get_notify_parameter();

                $this->handle_notify($notify);

                //----------业务逻辑结束---------------
                //告诉服务器已经收到通知
                if($notify['price'] == $notify['reallyPrice']){
                    echo 'success';

                    //$url = 'http://'.$_SERVER['HTTP_HOST'].'/pages/users/user_bill/index?type=2';
                    //header('Location: '.$url);
                }else{
                    echo '金额不正确，请联系处理';
                }

            }
            else
            {
                exit('fail');
            }
        }
        else
        {
            exit('fail');
        }

    }

    public function pay_return(){
        $ubomoney=$_GET["price"];
        $url ='http://'.$_SERVER['HTTP_HOST'].'/pages/users/user_bill/index?type=2';

        $template = <<<EOF
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Language" content="zh-cn">
    <meta name="apple-mobile-web-app-capable" content="no"/>
    <meta name="apple-touch-fullscreen" content="yes"/>
    <meta name="format-detection" content="telephone=no,email=no"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="white">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>支付详情</title>
    <link href="/wechat_pay.css" rel="stylesheet" media="screen">
    <style>
        .text-success {
            color: #468847;
            font-size: 2.33333333em;
        }

        .text-fail {
            color: #ff0c13;
            font-size: 2.33333333em;
        }

        .text-center {
            text-align: center;
        }

        .text-left {
            text-align: left;
        }

        .error {

            display: block;
            padding: 9.5px;
            margin: 0 0 10px;
            font-size: 13px;
            line-height: 1.42857143;
            color: #333;
            word-break: break-all;
            word-wrap: break-word;
            background-color: #f5f5f5;
            border: 1px solid #ccc;
            border-radius: 4px;

        }
    </style>
</head>

<body>
<div class="body">

    <div style="margin-top: 10vh">

        <h1 class="mod-title">
            <span class="ico_log " style="font-size: 2.4rem">支付成功</span>
        </h1>

        <div class="tip-text">
        </div>


    </div>
    <div class="foot">
        <div class="inner">
            <p>如未到账请联系我们</p>
        </div>
    </div>
</div>

<script>
     setTimeout(function () {
          window.location.href = '{$url}';
     }, 5000);//5秒后跳转
</script>
</body>
</html>
EOF;
        echo $template;
    }

    public function test()
    {
        echo 'test';
    }

}
